import { Compiler, Component, OnInit, Input, EventEmitter, Output, Host, Inject, forwardRef, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { HttpModule } from '@angular/http';
import { HttpClientModule, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { RouterModule, Router, ActivatedRoute } from '@angular/router';
import { Service } from '../../../server/server';
import { Pagination } from '../../../public/serve/pcrudInfo';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { UserRightService } from '../../../core/services/userright.service';
import * as _ from 'lodash';
declare var $: any;

interface Response {
  result: string[];
  result_code: string;
  message: string;
  length: number;
}

@Component({
  selector: 'app-role-limit',
  templateUrl: './role-limit.component.html',

})
export class RoleLimitComponent implements OnInit {
  public roleIdto: string;
  public operation_code: string[] = [];
  public permissionAll: string[] = [];
  public selectedData: any;
  public res: any;
  constructor(private compiler: Compiler, private http: HttpClient, private server: Service, private router: Router, private tableListService: CudTableService,private userRightService:UserRightService) {
    this.createUserId = this.server.getuser();
  }

  ngOnInit() {
    //接受角色Id
    this.rolebyeventEmit = this.server.rolebyeventEmit.subscribe((value: any) => {
      this.roleIdto = value;
      this.roleFn();
    });
  }

  //取消订阅
  public rolebyeventEmit: any;
  ngOnDestroy() {
    if (this.rolebyeventEmit ) {
      this.rolebyeventEmit.unsubscribe();
    }
  }

  public createUserId :any;

  async roleFn() {
    let urlRole = this.server.baseUrl+'user/functions/getRolePermissionList/' + this.roleIdto;
    let data = await this.tableListService.getRequest(urlRole).then((res: any) => {
      return res;
    });
    this.operation_code = [];
    for (var k = 0; k < data.result.length; k++) {
      this.operation_code.push(data.result[k]['operation_id'] + ":" + data.result[k]['functionId'])
    }
    // console.log(this.operation_code); // 用户权限数据
    let urlPermission = this.server.baseUrl+'user/functions/getPermissionList/';
    let result = await this.tableListService.getRequest(urlPermission).then((res: any) => {
      return res;
    });
    this.selectedData = [];
    this.selectedData = this.operation_code;
    this.permissionAll = [];
    for (var j = 0; j < result.result.length; j++) {
      if (result.result[j].permissionListes != null || result.result[j].permissionListes != "") {
        var permission = result.result[j].permissionListes.split(",");
        for (var i = 0; i < permission.length; i++) {
          var permissionId = permission[i].split(":");
          this.permissionAll.push(permissionId[0] + ":" + result.result[j].id);
        }
      }
    }
    this.res = [];
    this.res = this.permissionAll;
    var setting = {
      view: {
        addDiyDom: addDiyDom
      },
      data: {
        simpleData: {
          enable: true,
          idKey: "id",
          pIdKey: "pId",
          rootPId: 0
        },
        key: {
          checked: "isChecked"
        }
      },
    };

    let temp = this.operation_code;
    let selectedData = this.selectedData;

    // 动态在节点后面添加按钮
    function addDiyDom(treeId, treeNode) {
      var aObj = $("#" + treeNode.tId + "_a");
      if ($("#diyBtn_" + treeNode.id).length > 0) return;
      // 拆分权限列表 存放数组
      if (treeNode.permissionListes != null) {
        var treeCh = [];
        var permissArr = treeNode.permissionListes.split(",");
        for (var i = 0; i < permissArr.length; i++) {
          var permiss = permissArr[i].split(":");
          var editStrs;
          var tempPermiss = permiss[0] + ":" + treeNode.id;
          // 找到 ，存在
          if (temp.indexOf(tempPermiss) != -1) {
            selectedData.push(tempPermiss);
            editStrs = "<span class='pice' title="+ permiss[1] +">" + "<input type='checkbox'  checked='checked'  onclick='fnIsChecked(this)' value=" + permiss[0] + ":" + treeNode.id + ">" + "<lable class='permiss'>" + permiss[1] + "</lable>" + "</span>";
          } else {
            editStrs = "<span class='pice' title="+ permiss[1] +">" + "<input type='checkbox'   onclick='fnIsChecked(this)'  value=" + permiss[0] + ":" + treeNode.id + ">" + "<lable class='permiss' >" + permiss[1] + "</lable>" + "</span>";
          }
          treeCh.push(editStrs);
        }
        aObj.append(treeCh.toString().replace(/,/g, "  "));
        var btn = $("#diyBtn_" + treeNode.id);
        if (btn) btn.bind("click", function () { alert("diy Button for " + treeNode.name); });
      };
    }
    this.selectedData = selectedData;
    var zTree;
    var demoIframe;
    var treeObj = $("#tree");
    treeObj = $.fn.zTree.init(treeObj, setting, result.result);
    treeObj.expandAll(true);
    //取得所有节点
    var nodes = treeObj.getNodes();
  }

  checkAll() {
    $("ul input").each(function () {
      $(this).attr("checked", "");
      $("#selectedData").val($("#functionData").val());
    });
  }

  unCheckAll() {
    $("ul input").each(function () {
      $(this).removeAttr("checked");
      $("#selectedData").val("[]");
    });
  }

  ztreeExpandAll() {
    $.fn.zTree.getZTreeObj("tree").expandAll(true);
  }

  ztreeUnExpandAll() {
    $.fn.zTree.getZTreeObj("tree").expandAll(false);
  }

  public allright:any;

   submitTable() {
    let url = this.server.baseUrl+'user/functions/ModifierRolePermissionList';
    let roleId = $("#roleId").val();
    let selectedData = $("#selectedData").val();
    let data = { roleId: roleId, selectedData: selectedData };
    this.tableListService
      .postRequest(url, data)
      .then((res: any) => {
        //console.log(res)
        $("#permissionAssignment").modal("hide");
        if(res.result_code == '0000'){
          this.server.prompt = {prompt:true,success:true,fail:false,promptStatement:res.message};
          this.server.promptclose;
          this.allright = this.userRightService.refreshright();
          //console.log(this.allright)
          this.allright.then(value=>{
            this.server.refresheventEmit.emit(value);
            this.server.right = value;
            this.server.setRight(this.server.right);
          })

        }else{
          this.server.prompt = {prompt:true,success:false,fail:true,promptStatement:res.message};
          this.server.promptclose;
        }
      }).catch((err: string) => {
      });
  }

 
}


